package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.PermissionDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.exception.BusinessRuntimeException;
import com.itheima.pojo.Permission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author leboy
 * @description
 */
@Service
@Slf4j
public class PermissionServiceImpl implements PermissionService {

	@Autowired
	private PermissionDao permissionDao;
	@Override
	public PageResult findByPage(QueryPageBean queryPageBean) {
		// 开始分页
		PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize() );
		Page<Permission> page = permissionDao.findPermissionsByCondition(queryPageBean.getQueryString());
		return new PageResult(page.getTotal(),page);
	}

	private Boolean isExits(Permission permission){
		Permission p01 =  permissionDao.findPermissionByName(permission.getName());
		Permission p02 =  permissionDao.findPermissionByKeyword(permission.getKeyword());
		if (p01 == null && p02 == null){
			return false;
		}
		return true;
	}

	@Override
	public void add(Permission permission) {
		Boolean exits = isExits(permission);
		if (exits){
			throw new BusinessRuntimeException("此权限已存在，请检查");
		}
		permissionDao.add(permission);
	}

	@Override
	public void delById(Integer id) {
		// 是否被角色关联 关联不删除
		long count = permissionDao.findCountsByPermissionId(id);
		if(count != 0){
			log.debug("当前检查项被引用，不能删除!!!");
			throw new BusinessRuntimeException("当前权限被角色引用，不能删除!!!");
		}
		permissionDao.delById(id);
		log.debug("删除权限成功!!!");

	}

	@Override
	public Permission findById(Integer id) {
		return permissionDao.findById(id);
	}

	@Override
	public void edit(Permission permission) {
		Boolean exits = isExits(permission);
		if (exits){
			throw new BusinessRuntimeException("此权限已存在，请检查");
		}
		permissionDao.edit(permission);
	}

	@Override
	public List<Permission> findAll() {
		return permissionDao.findAll();
	}
}
